
var segundoReloj = 0;
// MUESTRA LA FECHA Y HORA
contSeg = 0;
fechaActualRel = new Date();
/*
Calendar s_now = Calendar.getInstance();
out.println("<script type='text/javascript'>");
out.println(" s_year = "+s_now.get(Calendar.YEAR));
out.println(" s_Month = "+s_now.get(Calendar.MONTH));
out.println(" s_DayOfMonth = "+s_now.get(Calendar.DAY_OF_MONTH));
out.println(" s_Hra = "+s_now.get(Calendar.HOUR_OF_DAY));
out.println(" s_Min = "+s_now.get(Calendar.MINUTE));
out.println(" s_Seg = "+s_now.get(Calendar.SECOND));
out.println(" s_MilSeg = "+s_now.get(Calendar.MILLISECOND));
out.println("</script>");
*/
// function muestraFechaHora(now_year,now_Month,now_DayOfMonth,now_Hra,now_Min,now_Seg,now_MilSeg){
/*now_year = 2012;
now_Month = 3;
now_DayOfMonth = 14;
now_Hra = 9;
now_Min = 10;
now_Seg = 1;
now_MilSeg = 0;*/

function showTime(now_year,now_Month,now_DayOfMonth,now_Hra,now_Min,now_Seg,now_MilSeg){
    var dayarray = new Array("Domingo","Lunes","Martes","Mi&eacute;rcoles","Jueves","Viernes","S&aacute;bado")
    var montharray = new Array("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre")
    if(contSeg > 0)
        fechaActualRel.setSeconds(segundoReloj+1);
    else
        fechaActualRel = new Date(now_year,now_Month,now_DayOfMonth,now_Hra,now_Min,now_Seg,now_MilSeg);
    var year = fechaActualRel.getYear();
    if (year < 1000)
        year += 1900;
    var day = fechaActualRel.getDay();
    var month = fechaActualRel.getMonth();
    var daym = fechaActualRel.getDate();
    if (daym < 10)
        daym = "" + daym;

    var hora = fechaActualRel.getHours();
    var minuto = fechaActualRel.getMinutes();
    segundoReloj = fechaActualRel.getSeconds();

    str_segundo = new String (segundoReloj);
    if (str_segundo.length == 1)
        str_segundo = "0" + segundoReloj;
    
    str_minuto = new String (minuto);
    if (str_minuto.length == 1)
        str_minuto = "0" + minuto;

    str_hora = new String (hora);
    if (str_hora.length == 1)
        str_hora = "0" + hora;

    horaImprimible = str_hora + " : " + str_minuto + " : " + str_segundo;
    document.getElementById("fechaServ").innerHTML = dayarray[day] + ", " + daym + " de " + montharray[month] + " del " + year;
    document.getElementById("horaServ").innerHTML = horaImprimible;
    contSeg++;
    setTimeout("showTime(0,0,0,0,0,0,0)",1000);
    
}
function showdate(mydate){
    var year = mydate.getYear()
    if (year < 1000)
     year += 1900
    var day = mydate.getDay()
    var month = mydate.getMonth()
    var daym = mydate.getDate()
    if (daym < 10)
     daym = "" + daym
    var dayarray = new Array("Domingo","Lunes","Martes","Mi&eacute;rcoles","Jueves","Viernes","S&aacute;bado")
    var montharray = new Array("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre")
    return dayarray[day] + ", " + daym + " de " + montharray[month] + " del " + year;
}
espacios = /^\s+$/;
//email = !(/\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/;
// ES LETRA?
function letras(campo) {
    var ubicacion;
    var caracteres = "abcdefghijklmnopqrstuvwxyzÃ± ABCDEFGHIJKLMNOPQRSTUVWXYZÃ‘Ã¡Ã©Ã­Ã³ÃºÃ�Ã‰Ã�Ã“Ãš";
    var contador = 0;
    for (var i=0; i < campo.length; i++) {
        ubicacion = campo.substring(i, i + 1);
        if (caracteres.indexOf(ubicacion) != -1) {
          contador++;
        } else {
          alert("ERROR: No se acepta el caracter '" + ubicacion + "'.");
          return false;
        }
    }
    return true;
}
// ES LETRA Y NUMERO?
function letras_Numeros(campo) {
    var ubicacion;
    var caracteres = "abcdefghijklmnopqrstuvwxyzÃ± ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789Ã‘Ã¡Ã©Ã­Ã³ÃºÃ�Ã‰Ã�Ã“Ãš.,:?Â¿=+()@!";
    var contador = 0;
    for (var i=0; i < campo.length; i++) {
        ubicacion = campo.substring(i, i + 1);
        if (caracteres.indexOf(ubicacion) != -1) {
          contador++;
        } else {
          alert("ERROR: No se acepta el caracter '" + ubicacion + "'.");
          return false;
        }
    }
    return true;
}
/*  METODODO QUE CONTROLAS LOS CARACRTERES INGRESADOS DESDE EL TECLADO
 *  SÃ³lo nÃºmeros
 *  <input type="text" id="texto" onkeypress="return permite(event, 'num')" />
 *  SÃ³lo letras
 *  <input type="text" id="texto" onkeypress="return permite(event, 'car')" />
 *  SÃ³lo letras o nÃºmeros
 *  <input type="text" id="texto" onkeypress="return permite(event, 'num_car')" />
**/
function permite(elEvento, permitidos) {
    // Variables que definen los caracteres permitidos
    var numeros = "0123456789.";
    var caracteres = " abcdefghijklmnÃ±opqrstuvwxyzABCDEFGHIJKLMNÃ‘OPQRSTUVWXYZ";
    var numeros_caracteres = numeros + caracteres;
    var teclas_especiales = [8, 37, 39, 46, 9]; // 9 = tabulador horizontal
    var digits = "0123456789";
    var numerosNegativos = "0123456789.-";
    // 8 = BackSpace, 46 = Supr, 37 = flecha izquierda, 39 = flecha derecha
    // Seleccionar los caracteres a partir del parÃ¡metro de la funciÃ³n
    switch(permitidos) {
        case 'num':
        permitidos = numeros;
        break;
        case 'car':
        permitidos = caracteres;
        break;
        case 'num_car':
        permitidos = numeros_caracteres;
        break;
        case 'digits':
        permitidos = digits;
        break;
        case 'numerosNegativos':
        permitidos = numerosNegativos;
        break;
    }
    // Obtener la tecla pulsada
    var evento = elEvento || window.event;
    var codigoCaracter = evento.charCode || evento.keyCode;
    var caracter = String.fromCharCode(codigoCaracter);
    // Comprobar si la tecla pulsada es alguna de las teclas especiales
    // (teclas de borrado y flechas horizontales)
    var tecla_especial = false;
    for(var i in teclas_especiales) {
        if(codigoCaracter == teclas_especiales[i]) {
            tecla_especial = true;
            break;
        }
    }
    // Comprobar si la tecla pulsada se encuentra en los caracteres permitidos
    // o si es una tecla especial
    return permitidos.indexOf(caracter) != -1 || tecla_especial;
}

// permit only digits
function onlyDigits(e){
	var code;
	if (!e) var e = window.event;
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	var character = String.fromCharCode(code);			
	    var AllowRegex  = /^[\b0-9\t]$/;
	    if (AllowRegex.test(character)) return true;     
	    return false; 
}

// METODO QUE CONVIERTE A FORMATO MYSQL. La entrada es una fecha ej: 05/01/2010
function aFormatoMysql(fecha){
    var dia = fecha.substring(0,2);
    var mes = fecha.substring(3,5);
    var anio = fecha.substring(6);
    return anio+"-"+mes+"-"+dia;
}

function redondea(valor, nDec){
    var n = parseFloat(valor);
    var s = "0.00";
    if (!isNaN(n)){
        n = Math.round(n * Math.pow(10, nDec)) / Math.pow(10, nDec);
        s = String(n);
        s += (s.indexOf(".") == -1? ".": "") + String(Math.pow(10, nDec)).substr(1);
        if(nDec != 0)
            s = s.substr(0, s.indexOf(".") + nDec + 1);
        else
            s = s.substr(0, s.indexOf("."));
    }
    return s;
} 
function parseDateBol(fecha){ //2011-12-22
    var dia = fecha.substring(8);
    var mes = fecha.substring(5,7);
    var anio = fecha.substring(0,4);
    return dia+"/"+mes+"/"+anio;
}

// ================================================================================
// ======= ESTE BLOQUE ES PARA CONVERTIR UN MONTO EN BOLIVIANOS A "LITERAL" =======
// ================================================================================
var unidades = new Array("","uno","dos","tres","cuatro","cinco","seis","siete","ocho","nueve","diez","once","doce","trece","catorce","quince");
var decenas = new Array("","diez","veint","treinta","cuarenta","cincuenta","sesenta","setenta","ochenta","noventa");
var centenas = new Array("","cien","doscientos","trescientos","cuatrocientos","quinientos","seiscientos","setecientos","ochocientos","novecientos");			

function getFormatoLiteral(numero){						
    var dollars = Math.floor(numero);		
    var monto = Math.floor(numero);
    var cents = parseInt(Math.round((numero*100 - dollars*100)),10);
    var thousands = (dollars - dollars % 1000) / 1000;
    dollars -= thousands * 1000;
    //alert("dollars: "+dollars+" monto: "+monto+" cents: "+cents+" thousands: "+thousands);
    var output = "";
    if ( monto >= 1000 ) {
        if ( monto < 2000 ) {
                output += "mil ";
        } else {
                output += num(thousands) + " mil ";
        }
    }
    output += (dollars > 0)?num(dollars) + "   " : "";
    output += ((cents < 10)? "0"+cents : cents)  +"/100";		
    //alert(output.substring(0,1).toUpperCase() + output.substring(1));
    return output.substring(0,1).toUpperCase() + output.substring(1);
}
function num(k){
    
    var j = parseInt(( (k - k % 100) / 100),10);
    var i = parseInt((k - j * 100),10);
    var cen = "";
    if ( j>0 ) {
        cen = centenas[j];
        cen += (j == 1 && i!=0) ? "to" : "";
        cen += (i > 0) ? " " : "";
    }
    if (i<16) return cen + unidades[i];
    var tens = parseInt(((i - i % 10) / 10),10);
    var units = parseInt((i - (i - i % 10)),10);
    if ( tens == 2 ) {
            return cen + decenas[tens] + ((units > 0) ? "i" : "e") + unidades[units];
    } else {
            return cen + decenas[tens] + ((tens > 0 && units > 0) ? " y " : "") + unidades[units];
    }		
}
// ====== FIN DEL BLOQUE CONVERTIR BOLIVIANOS A LITERAL o sea en letras



// add Rober
function roundNumber(n, d){
	var f = parseFloat(n);
	var r = Math.round(f*Math.pow(10,d))/Math.pow(10,d);
	return r;
}
function addZeroIfMinorToOther(val,otherNumber){
	var temp = (val < otherNumber)?('0'+val):(val);
	return temp;
}
// add Rober




// this to Dialog
function openDialogModalForm(elementIdentifier,title,callBack){
	$(elementIdentifier+" form").each(function(){
        this.reset();
    });
	if(!$(elementIdentifier+" h2").hasClass("decorado")){
		$(elementIdentifier+" form").before("<h2 class='decorado'>"+title+"</h2><br/>");
	}
    //$(elementIdentifier).dialog("destroy");
    $(elementIdentifier).dialog("open");
    $(elementIdentifier).dialog( "option", "title", title);
    if(callBack !== null){
    	callBack();
    }
}

function loadOptionTag(data,selector,itemSelected){
	var element = $(selector);
	element.empty().append("<option value='0'>Seleccione</option>");
	if(data[0].name != ''){
		for(var i=0; i<data.length; i++){
			var obj = data[i];
			element.append("<option value='"+obj.id+"'>"+obj.name+"</option>");
		}
	}
}


/* *******************Para mostrar los números en literales********************** */
// Función modulo, regresa el residuo de una división 
function mod(dividendo , divisor) 
{ 
		resDiv = dividendo / divisor ;  
	parteEnt = Math.floor(resDiv);            // Obtiene la parte Entera de resDiv 
		parteFrac = resDiv - parteEnt ;      // Obtiene la parte Fraccionaria de la división
		modulo = Math.round(parteFrac * divisor);  // Regresa la parte fraccionaria * la división (modulo) 
		return modulo; 
} // Fin de función mod

// Función ObtenerParteEntDiv, regresa la parte entera de una división
function ObtenerParteEntDiv(dividendo , divisor) 
{ 
		resDiv = dividendo / divisor ;  
		parteEntDiv = Math.floor(resDiv); 
		return parteEntDiv; 
} // Fin de función ObtenerParteEntDiv

// function fraction_part, regresa la parte Fraccionaria de una cantidad
function fraction_part(dividendo , divisor) 
{ 
		resDiv = dividendo / divisor ;  
		f_part = Math.floor(resDiv); 
		return f_part; 
} // Fin de función fraction_part

// function string_literal conversion is the core of this program 
// converts numbers to spanish strings, handling the general special 
// cases in spanish language. 
function string_literal_conversion(number) 
{   
		// first, divide your number in hundreds, tens and units, cascadig 
		// trough subsequent divisions, using the modulus of each division 
		// for the next. 
		centenas = ObtenerParteEntDiv(number, 100); 
		number = mod(number, 100); 

		decenas = ObtenerParteEntDiv(number, 10); 
		number = mod(number, 10); 

		unidades = ObtenerParteEntDiv(number, 1); 
		number = mod(number, 1);  
		string_hundreds="";
		string_tens="";
		string_units="";
		// cascade trough hundreds. This will convert the hundreds part to 
		// their corresponding string in spanish.
		if(centenas == 1){
  		string_hundreds = "ciento ";
		} 

		if(centenas == 2){
  		string_hundreds = "doscientos ";
		}

		if(centenas == 3){
  		string_hundreds = "trescientos ";
		} 

		if(centenas == 4){
  		string_hundreds = "cuatrocientos ";
		} 

		if(centenas == 5){
  		string_hundreds = "quinientos ";
		} 

		if(centenas == 6){
  		string_hundreds = "seiscientos ";
		} 

		if(centenas == 7){
  		string_hundreds = "setecientos ";
		} 

		if(centenas == 8){
  		string_hundreds = "ochocientos ";
		} 

		if(centenas == 9){
  		string_hundreds = "novecientos ";
		} 
		// end switch hundreds 

    // casgade trough tens. This will convert the tens part to corresponding 
    // strings in spanish. Note, however that the strings between 11 and 19 
    // are all special cases. Also 21-29 is a special case in spanish. 
	if(decenas == 1){
  		//Special case, depends on units for each conversion
   		if(unidades == 1){
     		string_tens = "once";
  		}
  
  		if(unidades == 2){
     		string_tens = "doce";
 		}
  
  		if(unidades == 3){
     		string_tens = "trece";
  		}
  
  		if(unidades == 4){
     		string_tens = "catorce";
  		}
  
  		if(unidades == 5){
     		string_tens = "quince";
  		}
  
  		if(unidades == 6){
     		string_tens = "dieciseis";
  		}
  
  		if(unidades == 7){
     		string_tens = "diecisiete";
  		}
  
  		if(unidades == 8){
     		string_tens = "dieciocho";
  		}
  
  		if(unidades == 9){
     		string_tens = "diecinueve";
  		}
		} 
		//alert("STRING_TENS ="+string_tens);

		if(decenas == 2){
  		string_tens = "veinti";
		}
		if(decenas == 3){
  		string_tens = "treinta";
		}
		if(decenas == 4){
  		string_tens = "cuarenta";
		}
		if(decenas == 5){
  		string_tens = "cincuenta";
		}
		if(decenas == 6){
  		string_tens = "sesenta";
		}
		if(decenas == 7){
  		string_tens = "setenta";
		}
		if(decenas == 8){
  		string_tens = "ochenta";
		}
		if(decenas == 9){
  		string_tens = "noventa";
		}
	// Fin de swicth decenas


    // cascades trough units, This will convert the units part to corresponding 
    // strings in spanish. Note however that a check is being made to see wether 
    // the special cases 11-19 were used. In that case, the whole conversion of 
    // individual units is ignored since it was already made in the tens cascade. 
	if (decenas == 1) 
		{ 
  		string_units="";  // empties the units check, since it has alredy been handled on the tens switch 
		} 
		else 
		{ 
  		if(unidades == 1){
     		string_units = "un";
  		}
  		if(unidades == 2){
     		string_units = "dos";
  		}
  		if(unidades == 3){
     		string_units = "tres";
  		}
  		if(unidades == 4){
     		string_units = "cuatro";
  		}
  		if(unidades == 5){
     		string_units = "cinco";
  		}
  		if(unidades == 6){
     		string_units = "seis";
  		}
  		if(unidades == 7){
     		string_units = "siete";
  		}
  		if(unidades == 8){
     		string_units = "ocho";
  		}
  		if(unidades == 9){
     		string_units = "nueve";
  		}
   		// end switch units 
		} // end if-then-else 


	//final special cases. This conditions will handle the special cases which 
	//are not as general as the ones in the cascades. Basically four: 
	
	// when you've got 100, you dont' say 'ciento' you say 'cien' 
	// 'ciento' is used only for [101 >= number > 199] 
	if (centenas == 1 && decenas == 0 && unidades == 0) 
	{ 
			string_hundreds = "cien " ; 
	}  

	// when you've got 10, you don't say any of the 11-19 special 
	// cases.. just say 'diez' 
	if (decenas == 1 && unidades ==0) 
	{ 
	   string_tens = "diez " ; 
	} 

	// when you've got 20, you don't say 'veinti', which is used 
	// only for [21 >= number > 29] 
	if (decenas == 2 && unidades ==0) 
	{ 
	  string_tens = "veinte " ; 
	} 

	// for numbers >= 30, you don't use a single word such as veintiuno 
	// (twenty one), you must add 'y' (and), and use two words. v.gr 31 
	// 'treinta y uno' (thirty and one) 
	if (decenas >=3 && unidades >=1) 
	{ 
	   string_tens = string_tens+" y "; 
	} 

	// this line gathers all the hundreds, tens and units into the final string 
	// and returns it as the function value.
	final_string = string_hundreds+string_tens+string_units;


	return final_string ; 

} //end of function string_literal_conversion()

// handle some external special cases. Specially the millions, thousands 
// and hundreds descriptors. Since the same rules apply to all number triads 
// descriptions are handled outside the string conversion function, so it can 
// be re used for each triad. 


function covertirNumLetras(number)
{
		principal=''; 
		number1=number;
		cent = number1.split('.');   
		centavos = cent[1];
		numerparchado=cent[0];
		if (centavos == 0 || centavos == undefined){
			centavos = "00";}

		if (number == 0 || number == "") 
		{ // if amount = 0, then forget all about conversions, 
  		centenas_final_string=" cero "; // amount is zero (cero). handle it externally, to 
  		// function breakdown 
		} 
		else{ 

 		millions  = ObtenerParteEntDiv(number, 1000000); // first, send the millions to the string 
  		number = mod(numerparchado, 1000000);           // conversion function 
  
 		if (millions != 0)
  		{                      
  			// This condition handles the plural case 
     		if (millions == 1) 
     		{ // if only 1, use 'millon' (million). if 
        		descriptor= " millon ";  // > than 1, use 'millones' (millions) as 
        	} 
     		else 
     		{ // a descriptor for this triad. 
          		descriptor = " millones "; 
        	} 
  		} 
  		else 
  		{    
     		descriptor = " ";    // if 0 million then use no descriptor. 
  		} 
  		millions_final_string = string_literal_conversion(millions)+descriptor; 
  		thousands = ObtenerParteEntDiv(number, 1000);  // now, send the thousands to the string 
    	number = mod(number, 1000);            // conversion function. 
  		//print "Th:".thousands;
 		if (thousands != 1) 
  		{    // This condition eliminates the descriptor 
     		thousands_final_string =string_literal_conversion(thousands) + " mil "; 
  		} 
  		if (thousands == 1)
  		{
     		thousands_final_string = " mil "; 
 		}
  		if (thousands < 1) 
  		{ 
     		thousands_final_string = " "; 
  		} 

	    // this will handle numbers between 1 and 999 which 
	    // need no descriptor whatsoever. 

	    centenas  = number;                     
	    centenas_final_string = string_literal_conversion(centenas) ; 
  
		} //end if (number ==0) 

		/* Concatena los millones, miles y cientos*/
		cad = millions_final_string+thousands_final_string+centenas_final_string; 

		/* Convierte la cadena a Mayúsculas*/
		cad = cad.toUpperCase();       
	if (centavos.length>2)
		{   
  		if(centavos.substring(2,3)>= 5){
     		centavos = centavos.substring(0,1)+(parseInt(centavos.substring(1,2))+1).toString();
  		}else{
    		centavos = centavos.substring(0,2);
   		}
		}

		/* Concatena a los centavos la cadena "/100" */
		if (centavos.length==1)
		{
  		centavos = centavos+"0";
		}
		centavos = centavos+ "/100"; 

		/* Asigna el tipo de moneda, para 1 = boliviano, para distinto de 1 = boliviano*/
		if (number == 1)
		{
  		moneda = " CON ";  
		}else{
  		moneda = " CON ";  
		}
		principal=cad+moneda+centavos+" Bolivianos ";
		return principal;
}

